import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router";
import type { ArticleView } from "../../../apis/article";
import apis from "../../../apis/article";
import useMeStore from "../../../store/me";

export default function ArticlePage() {
  const { id } = useParams();
  const [article, setArticle] = useState<ArticleView | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { me } = useMeStore();

  // 加载文章详情
  useEffect(() => {
    const loadArticle = async () => {
      if (!id) {
        setError("文章ID不存在");
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setError(null);
        const data = await apis.articleGet(id);
        setArticle(data);
      } catch (err) {
        setError("获取文章详情失败，请稍后再试");
        console.error("Failed to load article:", err);
      } finally {
        setLoading(false);
      }
    };

    loadArticle();
  }, [id]);

  // 检查当前用户是否是文章作者
  const isAuthor = React.useMemo(() => {
    if (!article?.author || me.type !== "ok") {
      return false;
    }
    // 这里假设author的nickname和当前用户的nickname相匹配表示是同一用户
    // 实际项目中可能需要使用更可靠的用户ID进行匹配
    return article.author.nickname === me.data.nickname;
  }, [article, me]);

  // 处理编辑按钮点击
  const _handleEdit = () => {
    // TODO: 编辑逻辑，这里使用Link跳转
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-base-100 flex flex-col items-center justify-center">
        <div className="loading loading-spinner loading-lg text-primary" />
        <p className="mt-4 text-base-content/70">加载文章中...</p>
      </div>
    );
  }

  if (error || !article) {
    return (
      <div className="min-h-screen bg-base-100 flex flex-col items-center justify-center p-4">
        <div className="max-w-md w-full bg-base-200 rounded-lg shadow-lg p-6 text-center">
          <div className="text-red-500 text-4xl mb-4">❌</div>
          <h2 className="text-xl font-semibold text-base-content mb-2">出错了</h2>
          <p className="text-base-content/70 mb-6">{error || "文章不存在"}</p>
          <Link
            to="/"
            className="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
          >
            返回首页
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-base-100">
      {/* 文章头部 */}
      <header className="bg-base-200 shadow-sm">
        <div className="max-w-4xl mx-auto px-4 py-6 sm:px-6">
          <div className="flex justify-between items-start">
            <h1 className="text-3xl font-bold text-base-content tracking-tight">{article.title}</h1>
            {isAuthor && (
              <Link
                to={`/articles/${id}/edit`}
                className="inline-flex items-center px-3 py-1.5 border border-primary text-sm font-medium rounded-md text-primary bg-primary/5 hover:bg-primary/10 transition-colors"
              >
                编辑文章
              </Link>
            )}
          </div>
          <div className="mt-4 flex items-center text-sm text-base-content/60">
            {article.author?.nickname && <span className="mr-4">作者：{article.author.nickname}</span>}
            <time dateTime={article.createdAt}>发布于：{new Date(article.createdAt).toLocaleDateString()}</time>
          </div>
        </div>
      </header>

      {/* 文章内容 */}
      <main className="max-w-4xl mx-auto px-4 py-8 sm:px-6">
        <article className="bg-base-200 shadow rounded-lg p-6 sm:p-8 prose max-w-none">
          <div className="prose prose-slate dark:prose-invert max-w-none">
            {/* 这里可以根据需要格式化文章内容，例如使用富文本编辑器的内容 */}
            <div className="my-4 text-base-content leading-relaxed">{article.content}</div>
          </div>
        </article>
      </main>

      {/* 返回按钮 */}
      <div className="max-w-4xl mx-auto px-4 py-6 sm:px-6">
        <Link
          to="/articles"
          className="inline-flex items-center px-4 py-2 border border-base-300 rounded-md shadow-sm text-sm font-medium text-base-content bg-base-200 hover:bg-base-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
        >
          ← 返回文章列表
        </Link>
      </div>
    </div>
  );
}
